﻿using System;
using System.Globalization;
using System.Transactions;
using DotNetNuke.Common;
using DotNetNuke.Framework;
using DotNetNuke.Modules._2DoTasks.Components;
using DotNetNuke.Modules._2DoTasks.Components.Controllers;
using DotNetNuke.Modules._2DoTasks.Components.Entities;
using DotNetNuke.Modules._2DoTasks.Components.ExceptionHandling;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules._2DoTasks
{
    public partial class SimpleTask : _2DoTasksModuleBase
    {
        #region "Events"

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            jQuery.RequestDnnPluginsRegistration();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //DotNetNuke.Framework.jQuery.RequestRegistration();
            //DotNetNuke.Framework.jQuery.RequestDnnPluginsRegistration();

            FillLanguage();
            this.Messages.ClearMessages();
            if (!Page.IsPostBack)
            {
                if (SimpleTask_Created)
                    Messages.ShowSuccess(Localization.GetString("SuccessAddTask", this.LocalResourceFile));
            }
        }

        /// <summary>
        /// Cancels the task creation and clears the form controls
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_cancel_Click(object sender, EventArgs e)
        {
            ClearControls();
        }

        /// <summary>
        /// Creates a new task
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_send_Click(object sender, EventArgs e)
        {
            Nullable<DateTime> completionDate;
            Nullable<int> projectId = null;

            if (Page.IsValid)
            {
                try
                {
                    using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
                    {
                        if (TaskParametersAreCorrectlyFilled(uof, out completionDate, out projectId))
                        {
                            TaskController taskController = new TaskController(uof);

                            //Set task fields
                            _Task task = new _Task
                            {
                                Name = txt_Name.Text.Trim(),
                                Description = string.Empty,
                                AssignedUserId = UserId,
                                RequestedByUserId = UserId,
                                TargetCompletiondate = completionDate,
                                TaskType = (int)SharedEnum.TaskType.Task,
                                TaskStatus = (int)SharedEnum.TaskStatus.Open,
                                Priority = (int)SharedEnum.TaskPriority.Low,
                                ProjectId = projectId
                            };
                            using (TransactionScope scope = new TransactionScope())
                            {
                                taskController.Add(task);
                                scope.Complete();
                            }
                            Response.Redirect(Globals.NavigateURL(PortalSettings.ActiveTab.TabID, string.Empty, "sTsk=1"));
                        }
                    }
                }
                catch (TaskValidationException exc)
                {
                    TaskController.InsertStatus status =
                        (TaskController.InsertStatus)Enum.Parse(typeof(TaskController.InsertStatus), exc.ErrorCode().ToString());

                    switch (status)
                    {
                        case TaskController.InsertStatus.CREATORNOTMEMBER:
                            Messages.ShowWarning(Localization.GetString("WarningCREATORNOTMEMBER", this.LocalResourceFile));
                            break;

                        case TaskController.InsertStatus.PROJECTNOTFOUND:
                            Messages.ShowWarning(Localization.GetString("WarningProjectNotFound", this.LocalResourceFile));
                            break;

                        default:
                            Exceptions.LogException(exc);
                            Messages.ShowError(Localization.GetString("ErrorAddTask", this.LocalResourceFile));
                            break;
                    }
                }
                catch (Exception exc)
                {
                    this.Messages.ShowError(Localization.GetString("ErrorAddTask", this.LocalResourceFile));
                    Exceptions.LogException(exc);
                }
            }
        }

        #endregion "Events"

        #region "Aux Functions"

        /// <summary>
        /// Evaluates if the fields for creating a new task are correctly filled
        /// </summary>
        /// <returns>returns true, if ok, false otherwise</returns>
        private bool TaskParametersAreCorrectlyFilled(UnitOfWork uof, out Nullable<DateTime> out_completionDate, out Nullable<int> out_projectId)
        {
            out_completionDate = null;
            out_projectId = null;

            if (txt_Name.Text.Trim().Equals(string.Empty))
            {
                Messages.ShowWarning(Localization.GetString("ValidationNameRequired", this.LocalResourceFile));
                return false;
            }

            if (txt_Name.Text.Length < 2)
            {
                Messages.ShowWarning(Localization.GetString("ValidationNameMinLenght", this.LocalResourceFile));
                return false;
            }

            if (txt_targetCompletiondate.Text != string.Empty)
            {
                try
                {
                    CultureInfo provider = CultureInfo.InvariantCulture;

                    out_completionDate = DateTime.ParseExact(txt_targetCompletiondate.Text, "dd-MM-yyyy", provider);
                }
                catch (Exception)
                {
                    Messages.ShowWarning(Localization.GetString("ValidationInvalidDate", this.LocalResourceFile));
                    return false;
                }
            }

            //if project field is passed, get the project id
            if (!txt_Project.Text.Trim().Equals(string.Empty))
            {
                //get the project with the passed name, so it can be associated to the task
                ProjectController prjController = new ProjectController(uof);
                _Project project = prjController.Get(txt_Project.Text.Trim());
                if (project == null)
                {
                    Messages.ShowWarning(Localization.GetString("WarningProjectNotFound", this.LocalResourceFile));
                    return false;
                }
                out_projectId = project.ProjectId;
            }

            return true;
        }

        /// <summary>
        /// Clears module controls to their default state
        /// </summary>
        private void ClearControls()
        {
            txt_Name.Text = string.Empty;
            txt_Project.Text = string.Empty;
            txt_targetCompletiondate.Text = string.Empty;
        }

        /// <summary>
        /// Fills the language data into the respective controls
        /// </summary>
        private void FillLanguage()
        {
            lbl_showHideForm.Text = Localization.GetString("lbl_showHideForm", this.LocalResourceFile);
            btn_send.Text = Localization.GetString("btn_send", this.LocalResourceFile);
            btn_cancel.Text = Localization.GetString("btn_cancel", this.LocalResourceFile);

            txt_Name.CssClass = string.Concat("validate:{required:true, minlength: 2, messages:{required:'",
                                               Localization.GetString("ValidationNameRequired", this.LocalResourceFile),
                                                    "', minlength:'",
                                                    Localization.GetString("ValidationNameMinLenght", this.LocalResourceFile),
                                                    "'}}");
        }

        #endregion "Aux Functions"
    }
}